package com.yangguang.huahui.ui.activitys;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.yangguang.huahui.Config;
import com.yangguang.huahui.R;
import com.yangguang.huahui.entity.DataInfo;
import com.yangguang.huahui.entity.PersonInfo;
import com.yangguang.huahui.entity.SelectData;
import com.yangguang.huahui.entity.Upload;
import com.yangguang.huahui.mvp.presenter.PersonInfoPresenter;
import com.yangguang.huahui.mvp.view.PersonInfoView;
import com.yangguang.huahui.ui.adapters.OnItemClickListener;
import com.yangguang.huahui.ui.adapters.ProvinceAdapter;
import com.yangguang.huahui.ui.adapters.SelectAdapter;
import com.yangguang.huahui.utils.CommonUtil;
import com.yangguang.huahui.utils.DialogUtil;
import com.yangguang.huahui.utils.ImageLoader;
import com.yangguang.huahui.utils.ImgDispose;
import com.yangguang.huahui.utils.LogUtil;
import com.yangguang.huahui.utils.SharedPreferenceUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.stefan.pickturelib.Pickture;

public class PersonInfoActivity extends BaseMvpActivity<PersonInfoView, PersonInfoPresenter> implements PersonInfoView {
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.iv_head)
    ImageView iv_head;//头像
    @BindView(R.id.tv_name)
    TextView tv_name;//名称
    @BindView(R.id.tv_address)
    TextView tv_address;//地址
    @BindView(R.id.tv_phone)
    TextView tv_phone;
    @BindView(R.id.tv_identity)
    TextView tv_identity;


    private Dialog dialog;
    List<String> imageList = new ArrayList<>();

    @OnClick({R.id.iv_back, R.id.iv_head, R.id.tv_name, R.id.mLL_name, R.id.mLL_phone, R.id.tv_phone, R.id.mLL_address,
            R.id.tv_address, R.id.mLL_identity, R.id.tv_identity})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_head:
                Pickture.with(mContext).max(1).hasCamera(true).selected(new ArrayList<String>()).create();
                break;
            case R.id.tv_name:
                startActivityForResult(new Intent(mContext, InputActivity.class)
                        .putExtra("input_content", tv_name.getText().toString())
                        .putExtra("input_title", "昵称")
                        .putExtra("input_length", 10)
                        .putExtra("input_type", 2), Config.INPUT_REQUEST_CODE);
                break;
            case R.id.mLL_name://昵称
                startActivityForResult(new Intent(mContext, InputActivity.class)
                        .putExtra("input_content", tv_name.getText().toString())
                        .putExtra("input_title", "昵称")
                        .putExtra("input_length", 10)
                        .putExtra("input_type", 2), Config.INPUT_REQUEST_CODE);
                break;
            case R.id.mLL_address:
                selectAddress();
                break;
            case R.id.tv_address:
                selectAddress();
                break;
            case R.id.mLL_phone:
                startActivityForResult(new Intent(mContext, InputActivity.class)
                        .putExtra("input_content", tv_phone.getText().toString())
                        .putExtra("input_title", "手机号")
                        .putExtra("edit_type", 101)
                        .putExtra("input_type", 6), Config.INPUT_REQUEST_CODE);
                break;
            case R.id.tv_phone://手机号码
                startActivityForResult(new Intent(mContext, InputActivity.class)
                        .putExtra("input_content", tv_phone.getText().toString())
                        .putExtra("input_title", "手机号")
                        .putExtra("edit_type", 101)
                        .putExtra("input_type", 6), Config.INPUT_REQUEST_CODE);
                break;
            case R.id.mLL_identity:
                setIdentity();
                break;
            case R.id.tv_identity://身份选择
                setIdentity();
                break;
        }
    }

    @Override
    protected int initLayoutId() {
        return R.layout.activity_person_info;
    }

    @Override
    protected void initView() {
        getArea();
        tv_title.setText(getString(R.string.person_info));
    }

    @Override
    protected void initData() {
        getSelectData(1);
    }

    @Override
    protected PersonInfoPresenter initPresenter() {
        return new PersonInfoPresenter();
    }

    @Override
    protected void fetchData() {
        mPresenter.getInfo(DataInfo.TOKEN);
        dialog = DialogUtil.showProgressDialog(mContext, getString(R.string.load_data));
    }

    @Override
    public void onSuccess(PersonInfo personInfo) {
        dialog.dismiss();
        ImageLoader.loadCircle(mContext, personInfo.getInfo().getAvatar(), iv_head);
        DataInfo.AVATARS = personInfo.getInfo().getAvatar();
        SharedPreferenceUtil.getInstance(mContext).putString(SharedPreferenceUtil.AVATARS, personInfo.getInfo().getAvatar());
        DataInfo.NICKNAME = personInfo.getInfo().getNickname();
        tv_name.setText(DataInfo.NICKNAME);
        tv_phone.setText(personInfo.getInfo().getPhone());
        for (SelectData.ListBean listBean : identity_datas) {
            if (listBean.getId().equals(personInfo.getInfo().getIdentity_id()))
                tv_identity.setText(listBean.getClassname());
        }
        tv_address.setText(personInfo.getInfo().getServicearea());
    }

    @Override
    public void onUploadImg(Upload upload) {
        if (upload.getUrl() != null) {
            LogUtil.e(upload.getUrl().get(0), true);
            ImageLoader.loadCircle(mContext, upload.getUrl().get(0), iv_head);
            mPresenter.editInfo(DataInfo.TOKEN, "avatar", upload.getUrl().get(0));
        }
    }

    @Override
    public void onError() {
        dialog.dismiss();
    }

    private void setIdentity() {
        View contentView = LayoutInflater.from(mContext).inflate(R.layout.dialog_list, null);
        ListView mListView = (ListView) contentView.findViewById(R.id.mListView);
        TextView tv_title = (TextView) contentView.findViewById(R.id.tv_title);
        tv_title.setText(getString(R.string.select_identity));
        LogUtil.e(identity_datas.get(0).getClassname(), true);
        SelectAdapter selectAdapter = new SelectAdapter(mContext, identity_datas, R.layout.select_list_item, new SelectAdapter.OnClickCallback() {
            @Override
            public void callBack(String id, String name) {
                tv_identity.setText(name);
                mPresenter.editInfo(DataInfo.TOKEN, "identity_id", id);
                alertDialog.dismiss();
            }
        });
        mListView.setAdapter(selectAdapter);
        show_bottom_dialog(contentView);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == Pickture.CODE_REQUEST) {
            // 将保存在本地的图片取出并缩小后显示在界面上
            Bitmap bitmap = handleCropResult((Activity) mContext, data);
//                iv_head.setImageBitmap(bitmap);
            LogUtil.e(data.getStringExtra("filePath"), true);
            mPresenter.uploadFile(ImgDispose.SaveBitmap(bitmap, data.getStringExtra("filePath")));
        }

        if (requestCode == Config.INPUT_REQUEST_CODE) {
            if (resultCode == Config.INPUT_RESULT_CODE) {
                switch (data.getIntExtra("input_type", 0)) {
                    case 2:
                        tv_name.setText(data.getStringExtra("input"));
                        mPresenter.editInfo(DataInfo.TOKEN, "nickname", data.getStringExtra("input"));
                        SharedPreferenceUtil.getInstance(mContext).putString(SharedPreferenceUtil.NICKNAME, data.getStringExtra("input"));
                        break;
                    case 6:
                        tv_phone.setText(data.getStringExtra("input"));
                        mPresenter.editInfo(DataInfo.TOKEN, "phone", data.getStringExtra("input"));
                        break;
                }
            }
        }
    }

    /**
     * 处理剪切后的返回值
     *
     * @param result
     */
    private Bitmap handleCropResult(Activity activity, Intent result) {
        if (result.getByteArrayExtra("bitmap") != null) {
            try {
                byte[] bis = result.getByteArrayExtra("bitmap");
                Bitmap bit_head = BitmapFactory.decodeByteArray(bis, 0, bis.length);
                return bit_head;
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            CommonUtil.myToastA(activity, "无法剪切选择图片");
        }
        return null;
    }

    private int fistPosition = -1;
    private int seconPosition = -1;
    private int thirdPosition = -1;
    String address_id = "";
    String address_name = "";
    private void selectAddress() {
        final List<String> list_id = new ArrayList<>();
        final List<String> list_name = new ArrayList<>();
        address_id = "";
        address_name = "";
        View contentView = LayoutInflater.from(mContext).inflate(R.layout.area_select, null);
        TextView tv_title = (TextView) contentView.findViewById(R.id.tv_input_title);
        tv_title.setText("地址");
        ListView lv_first = (ListView) contentView.findViewById(R.id.lv_first);
        ListView lv_second = (ListView) contentView.findViewById(R.id.lv_second);
        ListView lv_third = (ListView) contentView.findViewById(R.id.lv_third);
        ProvinceAdapter provinceAdapter = new ProvinceAdapter(mContext, mArea.getList(), R.layout.select_area_list_item,
                lv_second, lv_third, fistPosition, seconPosition, thirdPosition);
        provinceAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position, String id, String name) {
                fistPosition = position;
                if (!CommonUtil.isNull(id)) {
                    if (list_id.size() > 0) {
                        list_id.removeAll(list_id);
                    }
                    list_id.add(id);
                }
                if (!CommonUtil.isNull(name)) {
                    if (list_name.size() > 0) {
                        list_name.removeAll(list_name);
                    }
                    list_name.add(name);
                }
            }
        });
        ProvinceAdapter.CityAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position, String id, String name) {
                seconPosition = position;
                if (!CommonUtil.isNull(id)) {
                    if (list_id.size() == 2) {
                        list_id.remove(1);
                    } else if (list_id.size() == 3) {
                        list_id.remove(1);
                        list_id.remove(1);
                    }
                    list_id.add(id);
                }
                if (!CommonUtil.isNull(name)) {
                    if (list_name.size() == 2) {
                        list_name.remove(1);
                    } else if (list_name.size() == 3) {
                        list_name.remove(1);
                        list_name.remove(1);
                    }
                    list_name.add(name);
                }
            }
        });
        ProvinceAdapter.CityAdapter.AreaAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position, String id, String name) {
                thirdPosition = position;
                if (!CommonUtil.isNull(id)) {
                    if (list_id.size() == 3) {
                        list_id.remove(2);
                    }
                    list_id.add(id);
                }
                if (!CommonUtil.isNull(name)) {
                    if (list_name.size() == 3) {
                        list_name.remove(2);
                    }
                    list_name.add(name);
                }
            }
        });
        lv_first.setAdapter(provinceAdapter);
        show_dialog_max(contentView, (Activity) mContext);
        View.OnClickListener areaListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.iv_close:
                        alertDialog.dismiss();
                        break;
                    case R.id.iv_ok:
                        for (String name : list_name) {
                            address_name += name + "-";
                        }
                        if (address_name.length() > 0) {
                            address_name = address_name.substring(0, address_name.length() - 1);
                        }
                        tv_address.setText(address_name);
                        for (String name : list_id) {
                            address_id += name + ",";
                        }
                        if (address_id.length() > 0) {
                            address_id = address_id.substring(0, address_id.length() - 1);
                        }
                        mPresenter.editInfo(DataInfo.TOKEN, "servicearea", address_id);
                        alertDialog.dismiss();
                        break;
                }
            }
        };
        contentView.findViewById(R.id.iv_close).setOnClickListener(areaListener);
        contentView.findViewById(R.id.iv_ok).setOnClickListener(areaListener);
    }
}
